import os
from functools import cmp_to_key
import csv
import pandas as pd
import numpy as np

def count_lines(file_path):
    """
    读取一个.label有多少行
    参数是label文件的地址
    """
    with open(file_path, 'r') as file:
        lines = file.readlines()
        return len(lines)



def print_lines(file_path, line_indices):
    """
    读取一个label文件的一行并打印若干行
    """
    with open(file_path, 'r') as file:
        lines = file.readlines()

        for index in line_indices:
            print(lines[index].strip())


# 自定义排序函数，提取字符串中的数字部分并转换为整数
# 适用于eyediap
def extract_number(s):
    return int(''.join(filter(str.isdigit, s)))


def custom_compare(x, y):
    """
    sort的比较函数逻辑：两个字符串逐位比较排序
    适用于360,mpii,eth。不适用于eyediap
    """
    x_chars = list(x)
    y_chars = list(y)

    min_length = min(len(x_chars), len(y_chars))

    for i in range(min_length):
        x_char = x_chars[i]
        y_char = y_chars[i]
        if x_char.isdigit() and y_char.isdigit():
            x_num = int(x_char)
            y_num = int(y_char)
            if x_num != y_num:
                return x_num - y_num
        else:
            # Compare as ASCII values if at least one is not a digit
            if x_char != y_char:
                return ord(x_char) - ord(y_char)

    # If all characters are equal up to the minimum length, compare lengths
    return len(x_chars) - len(y_chars)


def merge_label(file_path, output_path):
    """
    将label文件合并为一个
    :param file_path:需要合并的label文件地址
    :param output_path:保存地址
    :return:
    """
    lines = []
    label_files = [file_name for file_name in os.listdir(file_path) if file_name.endswith('.label')]
    # 下面这一行是只对eyediap有用
    # label_files = sorted(label_files, key=lambda x: int(x.split('p')[1].split('.label')[0]))
    # 这行是对360以外的用
    # label_files = sorted(label_files, key=extract_number)
    # eyediap不能用
    label_files = sorted(label_files, key=cmp_to_key(custom_compare))
    for file_name in label_files:
        file = os.path.join(file_path, file_name)
        with open(file, 'r') as f:
            line = f.readlines()
            if line:
                # 去除首行的列名
                line.pop(0)
                lines.extend(line)
    with open(output_path, 'w') as output_file:
        output_file.writelines(lines)


def compare_csv_label(csv_path, label_path, image_index, gaze_index):
    """
    这个只适合于小数据集，大数据集会跑死机
    """
    csv_df = pd.read_csv(csv_path, header=None)
    with open(label_path, 'r') as file:
        label_data = file.readlines()
        label_data.pop(0)   # 视情况要与不要!!!
    label_data = [label.strip().split(" ") for label in label_data]
    results = []
    csv_index = 0
    label_index = 0
    while csv_index < len(csv_df) and label_index < len(label_data):
        csv_first_column = csv_df.iloc[csv_index, image_index]
        label_first_column = label_data[label_index][image_index]
        if csv_first_column == label_first_column:
            csv_gaze_column = csv_df.iloc[csv_index, gaze_index]
            label_second_column = label_data[label_index][gaze_index]
            if csv_gaze_column == label_second_column:
                results.append(1)
            else:
                results.append(0)
            csv_index += 1
            label_index += 1
        else:
            label_index += 1
    count_1 = results.count(1)
    count_0 = results.count(0)
    return f"{count_1}/{count_0}"

def compare_csv_label_new(csv_path, label_path, image_index, gaze_index):
    """
    这个就适合在大数据集上跑

    """
    # 1. 将label数据预加载为字典（仅需一次内存）
    label_dict = {}
    with open(label_path, 'r') as file:
        label_data = file.readlines()
        label_data.pop(0)   # 视情况要与不要!!!
        for row in label_data:
            row = row.strip().split(" ")
            key = row[image_index]
            label_dict[key] = row[gaze_index]

    # 2. 流式处理CSV文件（逐行读取）
    count_1 = 0
    count_0 = 0
    with open(csv_path, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            csv_key = row[image_index]
            csv_value = row[gaze_index]

            # 3. 字典快速查找比对
            label_value = label_dict.get(csv_key, None)
            if label_value is not None:
                if csv_value == label_value:
                    count_1 += 1
                else:
                    count_0 += 1

    return f"{count_1}/{count_0}"


def read_label_file_sorted(filename, id_index, gaze_index):
    """
    读取一个label文件，一列是索引(唯一)  一列是值
    :param filename:
    :param id_index:
    :param gaze_index:
    :return:字典形式的数据
    """
    data = {}
    with open(filename, 'r') as file:
        label_data = file.readlines()
        label_data.pop(0)
        for line in label_data:
            data_line = line.strip().split(" ")
            id = data_line[id_index]
            gaze = data_line[gaze_index]
            data[id] = gaze
    return dict(sorted(data.items()))


def compare_label_files_sorted(file1, file2):
    """
    比对两个字典中相同索引对应的数据
    file1是北航处理后的  file2是pnp-ga的
    :param file1:
    :param file2:
    :return:
    """
    count = 0
    data1 = read_label_file_sorted(file1, 3, 6)
    data2 = read_label_file_sorted(file2, 3, 1)

    common_indices = set(data1.keys()) & set(data2.keys())

    for index in common_indices:
        if data1[index] == data2[index]:
            count += 1
            # print(f"Index {index}: Matched - {data1[index]}")
        else:
            print(f"Index {index}: File1 - {data1[index]}, File2 - {data2[index]}")
    return count


def label_to_csv(label_file, csv_file, num_eyediap):
    """
    将.label文件转化为.csv文件，获得所有的目标域的csv文件
    landmark信息为0
    """
    with open(label_file, 'r') as file:
        lines = file.readlines() # 读取到了所有的label
    for line in lines:
        eye_landmarks = []
        for i in range(num_eyediap):         # mpiigaze是12个   360是6
            eye_landmarks.append(line.strip().split(" ")[i])
        for i in range(478):
            eye_landmarks.append(np.asarray(0.0))
            eye_landmarks.append(np.asarray(0.0))
        # 将关键点追加到csv文件
        with open(csv_file, mode='a', newline='') as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerow(eye_landmarks)


def add_face(input_file_path, output_file_path):
    """
    读取原来的label文件，然后在每一行的第一个元素中间添加/face
    """
    with open(input_file_path, 'r') as f:
        lines = f.readlines()

    modified_lines = []
    for line in lines:
        elements = line.strip().split(" ")
        elements[0] = elements[0].replace('\\', '/face/')
        modified_lines.append(' '.join(elements))

    with open(output_file_path, 'w') as f:
        f.write('\n'.join(modified_lines))


if __name__ == "__main__":
    # print(1111)
    # # count_lines函数的调用
    # file_path = r'D:\BaiduNetdiskDownload\FaceBased\eth\label\google_eth.label'
    # # file_path = r'D:\BaiduNetdiskDownload\FaceBased\Gaze360\resultLabel\result.label'
    # line_count = count_lines(file_path)
    # print(f'The file has {line_count} lines.')

    # print(2222)
    # # print_lines函数的调用
    # file_path = r'D:\BaiduNetdiskDownload\FaceBased\eth\label\train.label'
    # line_indices = [0, 1]
    # print_lines(file_path, line_indices)

    # print(3333)
    # file_path = "/home/xian/mzs/mzs_code/Dataset/diap_6400/Label"
    # output_path = "/home/xian/mzs/mzs_code/Dataset/diap_6400/all_noselect.label"
    # merge_label(file_path, output_path)

    # print(4444)
    # csv_path = r"F:\mzs_code\gaze_estimation\Dataset\eth\label\google_allImage_no_selecteth.csv"
    # label_path = r"D:\BaiduNetdiskDownload\FaceBased\eth\label\train.label"
    # result = compare_csv_label(csv_path, label_path, 0, 1)
    # print(result)

    # print(5555)
    # label_path_1 = "/home/xian/eyediap/EyeDiap_temp/Label"
    # label_path_2 = "/home/xian/PnP-GA-main/data"
    # label_files_1 = [file_name for file_name in os.listdir(label_path_1) if file_name.endswith('.label')]
    # label_files_1 = sorted(label_files_1, key=cmp_to_key(custom_compare))
    # label_files_2 = [file_name for file_name in os.listdir(label_path_2) if file_name.endswith('.label')]
    # label_files_2 = sorted(label_files_2, key=cmp_to_key(custom_compare))
    # for i in range(len(label_files_1)):
    #
    #     label_files_11 = os.path.join(label_path_1, label_files_1[i])
    #     label_files_22 = os.path.join(label_path_2, label_files_2[i])
    #     print(f"{i}, {label_files_11}, {label_files_22}")
    #     count = compare_label_files_sorted(label_files_11, label_files_22)
    #     print(count)

    # print(666)
    # label_file = '/home/xian/mzs/mzs_code/Dataset/eyediap_2025/all_noselect_diap.label'
    # csv_file = '/home/xian/mzs/mzs_code/Dataset/eyediap_2025/all_nolandmark_diap.csv'
    # num_eyediap = 11
    # label_to_csv(label_file, csv_file, num_eyediap)

    print(777)
    input_file_path = 'your_input_file.label'
    output_file_path = 'your_output_file.label'
    add_face(input_file_path, output_file_path)
